package Heap;

import java.util.Arrays;

public class GaoboHeap {
    public int[] elem;
    public int usedSize;
    public GaoboHeap () {
        elem = new int[11];
        usedSize = 0;
    }

    public void initiateArray (int[] arr) {
        this.elem = Arrays.copyOf(arr, arr.length);
        this.usedSize = arr.length;
    }

    public void creatHeap () {
        /**
         * 从下往上走，每次都通过shiftDown
         * 因为每次shiftDown都能使得当前parent下的堆是最小堆
         * 所以从下往上走一定能保证走到根结点的时候，所有子树都是最小堆
         */
        for (int parent = (usedSize - 2) / 2; parent >= 0; parent--) {
            shiftDown(parent, usedSize);
        }

    }

    public void swap(int a, int b) {
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }

    public void shiftDown (int parent, int len) {
        int child = parent * 2 + 1;
        while (child < len) {
            if (child + 1 < len && elem[child] > elem[child + 1]) {
                child++;
            }
            //孩子结点比父结点大 就没必要继续循环了？
            //剩下的孩子结点也不用比较了吗？？
            //可能是因为是从下网上走的，所以优先让子结点满足了堆的性质？
            if (elem[child] < elem[parent]) {
                swap(child, parent);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    public void shiftUp (int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[child] < elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public int poll () {
        if (usedSize == 0) {
            return -1;
        }
        int top = elem[0];
        elem[0] = elem[--usedSize];
        shiftDown(0, usedSize);
        return top;
    }

    public void offer (int x) {
        if (isFull()) {
            grow();
        }
        elem[usedSize++] = x;
        shiftUp(usedSize - 1);
    }

    public boolean isFull () {
        if (usedSize == elem.length) {
            return true;
        }
        return false;
    }

    public boolean isEmpty () {
        if (usedSize == 0) {
            return true;
        }
        return false;
    }

    public void grow () {
        if (elem.length < 64) {
            elem = Arrays.copyOf(elem, elem.length * 2);
        } else {
            elem = Arrays.copyOf(elem, elem.length + elem.length>>2);
        }
    }

    public void heapSort () {

    }
}
